package com.csw.flink.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo03ReadKafkaHadoop {

  def main(args: Array[String]): Unit = {

    /**
      * 读取kafka中的hadoop日志，实时分析
      */

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //创建配置文件对象
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    properties.setProperty("group.id", "csw1")
    properties.setProperty("auto.offset.reset", "earliest") //earliest：读取所有数据 latest：读取最新数据
    /**
      * 创建kafka消费者
      */
    val consumer = new FlinkKafkaConsumer[String]("hadoop.namenode", new SimpleStringSchema(), properties)


    val kafkaDS: DataStream[String] = env.addSource(consumer)


    val typeDS: DataStream[(String, Int)] = kafkaDS.filter(log => log.split(" ").length > 3).map(_.split(" ")(2)).map((_, 1)).keyBy(_._1).sum(1)

    typeDS.print()

    env.execute()
  }
}
